package com.ias.agdis_r.netservice.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;

import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.netservice.BaseService;
import com.ias.agdis_r.util.network.NetUtils;
import com.ias.agdis_r.util.S;

/**
 * wifi网服务
 * 
 * @author wanghu
 * 
 */
public class WifiNetService extends BaseService {
	private String sWifiNetIp = null;
	private String sPttServerIp = null;
	private String last_CTT = "";
	private String last_LCT = "";
	private int localSocketPort = 0;
	private String localSocketIp = "";
	
	// 获取wifi服务
	private WifiManager wifiManager = (WifiManager) context
			.getSystemService(Context.WIFI_SERVICE);

	public WifiNetService(Handler handler, Context context) {
		super(handler, context);
		//addToWifiList();
	}
	
	@Override
	public String getRestfulIP() {
		// TODO Auto-generated method stub
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		String SSID = wifiInfo.getSSID();
		if (S.isEmpty(SSID)) {
			return "";
		} else {
			String IP = "";
			ArrayList<HashMap<String, Object>> wifilist = getWifiList();
			for (int j = 0; j < wifilist.size(); j++) {
				String mssid = wifilist.get(j).get("txt_ssid").toString();
				if (SSID.equals(mssid)||SSID.equals("\""+mssid+"\"")) {
					IP = wifilist.get(j).get("txt_ip_restful").toString();
					break;
				}
			}
			return IP;
		}
	}
	
	@Override
	public String getPushIP() {
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		String SSID = wifiInfo.getSSID();
		if (S.isEmpty(SSID)) {
			return "";
		} else {
			String IP = "";
			ArrayList<HashMap<String, Object>> wifilist = getWifiList();
			for (int j = 0; j < wifilist.size(); j++) {
				String mssid = wifilist.get(j).get("txt_ssid").toString();
				if (SSID.equals(mssid)||SSID.equals("\""+mssid+"\"")) {
					IP = wifilist.get(j).get("txt_ip_push").toString();
					break;
				}
			}
			return IP;
		}
	}

	@Override
	protected int getPushPort() {
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		String SSID = wifiInfo.getSSID();
		if (S.isEmpty(SSID)) {
			return 0;
		} else {
			int port = 0;
			String PORT = "";
			ArrayList<HashMap<String, Object>> wifilist = getWifiList();
			for (int j = 0; j < wifilist.size(); j++) {
				String mssid = wifilist.get(j).get("txt_ssid").toString();
				if (SSID.equals(mssid)||SSID.equals("\""+mssid+"\"")) {
					PORT = wifilist.get(j).get("txt_port_push").toString();
					if (S.isNotEmpty(PORT)) {
						port = Integer.parseInt(PORT);
						break;
					}
				}
			}
			return port;
		}
	}
	@Override
	public int getRestfulPort() {
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		String SSID = wifiInfo.getSSID();
		if (S.isEmpty(SSID)) {
			return 0;
		} else {
			int port = 0;
			String PORT = "";
			ArrayList<HashMap<String, Object>> wifilist = getWifiList();
			for (int j = 0; j < wifilist.size(); j++) {
				String mssid = wifilist.get(j).get("txt_ssid").toString();
				if (SSID.equals(mssid)||SSID.equals("\""+mssid+"\"")) {
					PORT = wifilist.get(j).get("txt_port_restful").toString();
					if (S.isNotEmpty(PORT)) {
						port = Integer.parseInt(PORT);
						break;
					}
				}
			}
			return port;
		}
	}
	private NetworkInfo getWifi(){
		ConnectivityManager manger = (ConnectivityManager) context
		.getSystemService(Context.CONNECTIVITY_SERVICE);
		return manger.getNetworkInfo(1);
	}
	@Override
	public boolean connectting() {
		return getWifi().getState() == NetworkInfo.State.CONNECTING;
	}
	/**
	 * WIFI获取IP地址
	 */
	@Override
	public String getLocalIpAddress() {

		return sWifiNetIp;
	}

	/**
	 * 获取wifi列表数据
	 */
	@Override
	protected ArrayList<HashMap<String, Object>> getWifiList() {
		ArrayList<HashMap<String, Object>> mylist = new ArrayList<HashMap<String, Object>>();
//		String[] ID = DataBaseManager.getInstance().getString(
//				ParameterModel.T_WIFI_INFO, ParameterModel.NET_ID).split(
//				",");
		String[] SSID = DataBaseManager.getInstance().getString(
				ParameterModel.T_WIFI_INFO, ParameterModel.NET_SSID).split(
				",");
		String[] PSW = DataBaseManager.getInstance().getString(
				ParameterModel.T_WIFI_INFO, ParameterModel.NET_PASSWORD)
				.split(",");
		String[] IP_PUSH = DataBaseManager.getInstance().getString(
				ParameterModel.T_WIFI_INFO, ParameterModel.NET_IP_PUSH).split(
				",");
		String[] IP_RESTFUL = DataBaseManager.getInstance().getString(
				ParameterModel.T_WIFI_INFO, ParameterModel.NET_IP_RESTFUL).split(
				",");
		String[] PORT_PUSH = DataBaseManager.getInstance().getString(
				ParameterModel.T_WIFI_INFO, ParameterModel.NET_PORT_PUSH).split(
				",");
		String[] PORT_RESTFUL = DataBaseManager.getInstance().getString(
				ParameterModel.T_WIFI_INFO, ParameterModel.NET_PORT_RESTFUL).split(
				",");
		for (int i = 0; i < SSID.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			if (i >= IP_PUSH.length)
				break;
			if (i >= SSID.length)
				break;
			if (i >= PORT_PUSH.length)
				break;
			//目前暂时只设置一个WIFI配置，暂时读取T_WIFI_INFO信息
			map.put("txt_ID", "1");
			map.put("txt_ssid", SSID[i]);
			map.put("txt_password", PSW[i]);
			map.put("txt_ip_push", IP_PUSH[i]);
			map.put("txt_ip_restful", IP_RESTFUL[i]);
			map.put("txt_port_push", PORT_PUSH[i]);
			map.put("txt_port_restful", PORT_RESTFUL[i]);
			mylist.add(map);
		}
		return mylist;
	}

	/**
	 * 将数据库中AP数据加入到系统WIFI列表
	 */
	private void addToWifiList() {
		ArrayList<HashMap<String, Object>> wifilist = getWifiList();
		disConnect();
		for (int x = 0; x < wifilist.size(); x++) {
			String ssid = S.valueOf(wifilist.get(x).get("txt_ssid").toString());
			String pwd = S.valueOf(wifilist.get(x).get("txt_password")
					.toString());
			boolean configuredExisted = false;
			boolean scanresultExisted = false;
			String type = "";
			for (int i = 0; i < wifiManager.getConfiguredNetworks().size(); i++) {
				String ss = wifiManager.getConfiguredNetworks().get(i).SSID;
				WifiConfiguration cfg = wifiManager.getConfiguredNetworks()
						.get(i);
				if (cfg.SSID.equals("\"" + ssid + "\"")) {
					configuredExisted = true;
					cfg.preSharedKey = "\"" + pwd + "\"";
					cfg.wepKeys[0] = "\"" + pwd + "\""; // This is the WEP
					cfg.wepTxKeyIndex = 0;
				}
			}
			if (!configuredExisted) {
				List<ScanResult> scanresult = wifiManager.getScanResults();
				if (scanresult != null) {
					for (int i = 0; i < scanresult.size(); i++) {
						// 获取将ScanResult信息
						// 其中把包括：BSSID、SSID、capabilities、frequency、level
						String mssid = scanresult.get(i).SSID;
						if (mssid.equals(ssid)) {
							scanresultExisted = true;
							String capabilities = scanresult.get(i).capabilities;
							if (capabilities.contains(NetUtils.ScanResult_WPA)) {
								type = NetUtils.WifiConfiguration_WPA_WPA2_PSK;
							} else {
								type = NetUtils.WifiConfiguration_WEP;
							}
						}
					}
				}
			} 
//			if (scanresultExisted) {
//				// 加入到AP列表
//				// 见http://stackoverflow.com/questions/4374862/how-to-programatically-create-and-read-wep-eap-wifi-configurations-in-android/4374934#4374934
//				if (type.equals(NetUtils.WifiConfiguration_WPA_WPA2_PSK)) {
//					// 新增wpa/wpa2 psk
//					WifiConfiguration wc = new WifiConfiguration();
//					wc.SSID = "\"" + ssid + "\"";// wc.SSID =
//					// "\"TP-LINK_69A38E\"";
//					wc.allowedAuthAlgorithms
//							.set(WifiConfiguration.AuthAlgorithm.OPEN);
//					wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
//					wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
//					wc.allowedKeyManagement
//							.set(WifiConfiguration.KeyMgmt.WPA_PSK);
//					wc.allowedPairwiseCiphers
//							.set(WifiConfiguration.PairwiseCipher.CCMP);
//					wc.allowedPairwiseCiphers
//							.set(WifiConfiguration.PairwiseCipher.TKIP);
//					wc.allowedGroupCiphers
//							.set(WifiConfiguration.GroupCipher.CCMP);
//					wc.allowedGroupCiphers
//							.set(WifiConfiguration.GroupCipher.TKIP);
//					wc.preSharedKey = "\"" + pwd + "\"";
//					wc.hiddenSSID = true;
//					wc.status = WifiConfiguration.Status.ENABLED;
//					int res = wifiManager.addNetwork(wc);
//				} else if (type.equals(NetUtils.WifiConfiguration_WEP)) {
//					// wep
//					WifiConfiguration wc = new WifiConfiguration();
//					wc.SSID = "\"" + ssid + "\""; // IMP! This should be in
//					// Quotes!!
//					wc.allowedAuthAlgorithms
//							.set(WifiConfiguration.AuthAlgorithm.OPEN);
//					wc.allowedAuthAlgorithms
//							.set(WifiConfiguration.AuthAlgorithm.SHARED);
//					wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
//					wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
//					wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//					wc.allowedPairwiseCiphers
//							.set(WifiConfiguration.PairwiseCipher.CCMP);
//					wc.allowedPairwiseCiphers
//							.set(WifiConfiguration.PairwiseCipher.TKIP);
//					wc.allowedGroupCiphers
//							.set(WifiConfiguration.GroupCipher.WEP40);
//					wc.allowedGroupCiphers
//							.set(WifiConfiguration.GroupCipher.WEP104);
//					wc.wepKeys[0] = "\"" + pwd + "\""; // This is the WEP
//					// Password
//					wc.hiddenSSID = false;
//					wc.status = WifiConfiguration.Status.ENABLED;
//					wc.priority = 40;
//					wc.wepTxKeyIndex = 0;
//					int res = wifiManager.addNetwork(wc);
//				}
//				wifiManager.saveConfiguration();
//			}
		}
	}

	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + (i >> 24 & 0xFF);
	}

	/**
	 * 连接此AP
	 * 
	 * @param ssid
	 * @param pwd
	 * @return
	 */
	private boolean AddNetwork(String ssid, String pwd) {
		if (S.isEmpty(ssid)) {
			return false;
		}

		boolean success = false;
		for (int i = 0; i < wifiManager.getConfiguredNetworks().size(); i++) {
			WifiConfiguration cfg = wifiManager.getConfiguredNetworks().get(i);
			if (cfg.SSID.equals("\"" + ssid + "\"")) {
				int wcgID = cfg.networkId;
				cfg.preSharedKey = "\"" + pwd + "\"";
				cfg.wepKeys[0] = "\"" + pwd + "\"";
				cfg.wepTxKeyIndex = 0;
				success = wifiManager.enableNetwork(wcgID, true);
				break;
			}
		}
		return success;
	}

	// 断开当前WIFI
	private void disConnect() {
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		if (wifiInfo != null && wifiInfo.getNetworkId() != -1) {
			DisconnectWifi(wifiInfo.getNetworkId());
		}
	}
	
	// 断开指定ID的网络
	private void DisconnectWifi(int netId) {
		wifiManager.disableNetwork(netId);
		wifiManager.disconnect();
	}

	// 得到WifiInfo的所有信息包
	public WifiInfo GetWifiInfo() {
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		return (wifiInfo == null) ? null : wifiInfo;
	}

	/**
	 * 扫描，刷新热点
	 */
	// private void StartScan() {
	// wifiManager.startScan();
	// }

	/**
	 * 获取型号强度
	 */
	private int getSinganlLevel(int rssi, int numLevels) {
		return WifiManager.calculateSignalLevel(rssi, numLevels);
	}

	/**
	 * 得到扫描结果
	 * 
	 * @return
	 */
	private ArrayList<HashMap<String, Object>> getUsefullScanWifiList() {
		wifiManager.startScan();
		ArrayList<HashMap<String, Object>> wifilistresult = null;
		List<ScanResult> scanresult = wifiManager.getScanResults();
		if (scanresult != null) {
			// scanresult = sortWifi(scanresult);
			wifilistresult = sortDataBaseWifi(scanresult);
		}
		return wifilistresult;
	}

	/**
	 * wifi信号强弱排序
	 * 
	 * @param _scanresult
	 */
	private List<ScanResult> sortWifi(List<ScanResult> _scanresult) {
		// ScanResult temp;
		// for (int m = 0; m < _scanresult.size(); m++) {// sort
		// for (int n = m + 1; n < _scanresult.size() - 1; n++) {
		// int nSinganlLevel = getSinganlLevel(_scanresult.get(n).level,
		// 10);
		// int mSinganlLevel = getSinganlLevel(_scanresult.get(m).level,
		// 10);
		// if (nSinganlLevel < mSinganlLevel) {
		// temp = _scanresult.get(n);
		// _scanresult.set(n, _scanresult.get(m));
		// _scanresult.set(m, temp);
		// }
		// }
		// }
		String b = "";
		for (int m = 0; m < _scanresult.size(); m++) {// sort
			b = b + _scanresult.get(m).SSID + _scanresult.get(m).capabilities
					+ "\n";
		}
		String c = b;
		return _scanresult;
	}

	/**
	 * 本地数据库AP根据信号强弱排序
	 * 
	 * @param scanresult
	 * @return
	 */
	private ArrayList<HashMap<String, Object>> sortDataBaseWifi(
			List<ScanResult> scanresult) {
		ArrayList<HashMap<String, Object>> wifilistresult = new ArrayList<HashMap<String, Object>>();
		ArrayList<HashMap<String, Object>> wifilist = getWifiList();
		for (int i = 0; i < scanresult.size(); i++) {
			// 获取将ScanResult信息
			// 其中把包括：BSSID、SSID、capabilities、frequency、level
			String mssid = scanresult.get(i).SSID;

			for (int j = 0; j < wifilist.size(); j++) {
				String mssid1 = wifilist.get(j).get("txt_ssid").toString();
				if (mssid.equals(mssid1)) {
					wifilistresult.add(wifilist.get(j));
				}
			}
		}
		return wifilistresult;
	}
	
	public int getNetIndex() {
		return 31;
	}
	
	public void setLocalAddress(String _sNetIp) {
		this.sWifiNetIp = _sNetIp;
	}

	@Override
	public String getLastCCT() {
		// TODO Auto-generated method stub
		return last_CTT;
	}

	@Override
	public String getLastLCT() {
		// TODO Auto-generated method stub
		return last_LCT;
	}

	@Override
	public void setLastCCT(String cct) {
		// TODO Auto-generated method stub
			this.last_CTT = cct;
	}

	@Override
	public void setLastLCT(String lct) {
		// TODO Auto-generated method stub
			this.last_LCT = lct;
	}

	@Override
	public int getLocalSocketPort() {
		// TODO Auto-generated method stub
		return this.localSocketPort;
	}

	@Override
	public void setLocalSocketPort(int port) {
		// TODO Auto-generated method stub
		this.localSocketPort = port;
	}
	@Override
	public String getLocalSocketIp() {
		return this.localSocketIp;
	}
	@Override
	public void setLocalSocketIp(String localSocketIp) {
		this.localSocketIp = localSocketIp;
	}
}
